#!/usr/bin/env python

import numpy as np
import os, serial,time,socket,sys,json
from meas_data import meas_data
# import the server implementation

sensor="ads1x15"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":50,"check_last_shrinking":0.9,"gpg_keyid":"","digits":4,"store_dir":"/home/pi/log/","multiplicator":1,"sensor":sensor,"sigma":3}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]

bsensor=False
if sensor in log_conf:
	if "enable" in log_conf[sensor]:
		if log_conf[sensor]["enable"] == 1:
			bsensor=True


# declare adc
badc=False
channel_info={}
GAIN=1
if bsensor:
  badc=True
  ads_conf=log_conf['ads1x15']
  if "enable" in ads_conf:
    for n in parameter:
      if n in log_conf['ads1x15']:
        parameter[n]=log_conf['ads1x15'][n]
    if ads_conf['enable'] == 0:
      badc=False
  bmqtt=False
  if "mqtt" in log_conf:
    bmqtt=True
    lcmq=log_conf['mqtt']
    mbroker=""
    if 'broker' in lcmq:
      mbroker=lcmq['broker']
    else:
      bmqtt=False
    mport=1883
    if 'port' in lcmq:
      mport=lcmq['port']  
  if "sqlserver" in log_conf:
    hostname="localhost"
    port=8080
  if badc:
    adc={}
    GAIN=1
    for n in parameter:
      if n in ads_conf:
        parameter[n]=ads_conf[n]
    if "gain" in ads_conf:
      GAIN=ads_conf['gain']
    if "adc" in ads_conf:
      tsl_sigma=parameter['sigma']
      if "sigma" in log_conf['ads1x15']:
        tsl_sigma=int(log_conf['ads1x15']['sigma'])
        if tsl_sigma < 1:
          tsl_sigma=1
        parameter["sigma"]=tsl_sigma
      from Adafruit_ADS1x15 import ADS1115
      from Adafruit_ADS1x15 import ADS1015
      adc_count=0
      tadc=ads_conf['adc']
      for x in tadc:
        varpar=parameter
        y=tadc[x]
        adc_address=0x48
        if "address" in y:
          adc_address=int(y['address'],16)
        abc_bus=1
        if "busnum" in y:
          adc_bus=y['busnum']
        adc_type=1015
        if "type" in y:
          adc_type=y['type']
        adc_assigned=False
        if adc_type == 1115:
          try:
            adc[adc_count]=ADS1115(address=adc_address,busnum=adc_bus)
            adc_assigned=True
          except:
            print("could not assign ADC")
        if adc_type == 1015:
          try:
            adc[adc_count]=ADS1015(address=adc_address,busnum=adc_bus)
            adc_assigned=True
          except:
            print("could not assign ADC")
        varpar["sensor"]="ads"+str(adc_type)
        varpar["i2c"]=adc_address
        if adc_assigned:
          for j in range(4):
            cnadc="a"+str(adc_count)+"_"+str(j)
            cnadcs="a"+"_"+str(j)
#            channel_names.append(cnadc)
            varrpar=varpar
            varrpar["var_name"]=cnadcs
            channel_info[cnadc]={"meas_data": meas_data(varrpar)}
            if bmqtt and ("mqtt" in log_conf['ads1x15']):
              channel_info[cnadc]['meas_data'].set_mqtt(broker=mbroker,port=mport)
            if "sqlserver" in log_conf:
              channel_info[cnadc]['meas_data'].set_sql(host=hostname,port=port)
          adc_count=adc_count+1
    else:
      badc=False


if badc:
      
  while True:
  
    for i in adc:
      cname="a"+str(i)+"_{0}"
      for j in range(4):
        channel_info[cname.format(j)]['meas_data'].append(adc[i].read_adc(j,gain=GAIN))

    time.sleep(parameter['wait'])


# close the client
print("done")


